package com.letv.whatslive.web.controller.video;

import com.google.common.collect.Lists;
import com.le.luffi.media.model.db.Pagination;
import com.le.luffi.media.model.db.Video;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.constant.ProgramConstants;
import com.letv.whatslive.web.bean.VideoDTS;
import com.letv.whatslive.web.controller.PubController;
import com.letv.whatslive.web.service.video.VideoService;
import com.letv.whatslive.web.util.String.StringUtils;
import com.letv.whatslive.web.util.util.BeanUtils;
import com.letv.whatslive.web.util.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 直播Controller
 * Created by wangjian7 on 2015/7/10.
 */

@Controller
@RequestMapping("/video")
public class VideoController extends PubController {

    private static final Logger logger = LoggerFactory.getLogger(VideoController.class);
    @Autowired
    private VideoService videoService;


    /**
     * 显示直播列表页面
     *
     * @return ModelAndView
     */
    @RequestMapping("/live")
    public ModelAndView live() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/video/live");
        modelAndView.addObject("videoType", ProgramConstants.pType_live);
        return modelAndView;
    }
    /**
     * 详情
     *
     * @return ModelAndView
     */
    @RequestMapping("/live/details")
    public ModelAndView details(WebRequest webRequest) {
        Video video = new Video();
        Long id = ObjectUtils.toLong(webRequest.getParameter("id"));
        video.setId(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/video/live_details");
        Pagination<Video> videoPagination  = videoService.findAllByParam(null, video, 1L, 1);
        VideoDTS videoDTS = new VideoDTS();
        Video video1 =  videoPagination.getData().get(0);
        BeanUtils.copyProperties(video1, videoDTS);
       videoDTS.setStr_startTime(DateUtils.formateLong2Date(DateUtils.DATA_FORMAT_3, ObjectUtils.toLong(videoDTS.getStartTime())));
        videoDTS.setStr_endTime(DateUtils.formateLong2Date(DateUtils.DATA_FORMAT_3, ObjectUtils.toLong(videoDTS.getEndTime())));
         videoDTS.setStr_createTime(DateUtils.getFormatDate(videoDTS.getCreateTime(), DateUtils.DATA_FORMAT_3));
        videoDTS.setStr_updateTime(DateUtils.getFormatDate(videoDTS.getUpdateTime(), DateUtils.DATA_FORMAT_3));
        //添加国家在StringUtils里
        videoDTS.setStr_dispatchBusinessId(StringUtils.replaceDispatchBusinessId(video1.getDispatchBusinessId()));
        modelAndView.addObject("videoDTS", videoDTS);
        return modelAndView;
    }

    /**
     * 显示重播列表页面
     *
     * @return ModelAndView
     */
    @RequestMapping("/relive")
    public ModelAndView relive() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/video/live");
        modelAndView.addObject("videoType", ProgramConstants.pType_order);
        return modelAndView;
    }

    /**
     * 查询直播列表
     *
     * @param valueMap
     * @param response
     * @return Map<String, Object>
     */
    @RequestMapping("/list.json")
    @ResponseBody
    public Map<String, Object> list(@RequestBody MultiValueMap valueMap, HttpServletResponse response) {
        Video video = new Video();
        Map<String, Object> param = valueMap.toSingleValueMap();
        Long start = ObjectUtils.toLong(param.get("iDisplayStart"));
        Integer limit = ObjectUtils.toInteger(param.get("iDisplayLength"));
        String sEcho = ObjectUtils.toString(param.get("sEcho"));
        //查询过滤条件
        String search_videoTitle = ObjectUtils.toString(param.get("search_videoTitle"));
        String search_sourceCountry = ObjectUtils.toString(param.get("search_sourceCountry"));
        String search_videoType = ObjectUtils.toString(param.get("search_videoType"));
        if (StringUtils.isNotBlank(search_videoTitle)) {
            video.setTitle(search_videoTitle);
        }
        if (StringUtils.isNotBlank(search_sourceCountry)) {
            video.setSourceCountry(search_sourceCountry);
        }
        if (StringUtils.isNotBlank(search_videoType)) {
            video.setType(ObjectUtils.toInteger(search_videoType));
        }
        Pagination<Video> videoPagination = videoService.findAllByParam(null, video, start / limit + 1, limit);
        List<VideoDTS> videoDTSList = Lists.newArrayList();
        for(Video video1: videoPagination.getData()){
                VideoDTS videoDTS = new VideoDTS();
                BeanUtils.copyProperties(video1, videoDTS);
                //videoDTS.setStr_startTime(DateUtils.parse2String(video1.getCreateTime()));
            videoDTS.setStr_startTime(DateUtils.formateLong2Date(DateUtils.DATA_FORMAT_3, ObjectUtils.toLong(videoDTS.getStartTime())));
                //添加国家在StringUtils里
                videoDTS.setStr_dispatchBusinessId(StringUtils.replaceDispatchBusinessId(video1.getDispatchBusinessId()));
                videoDTSList.add(videoDTS);
        }
        Map<String, Object> result = getSuccessMap();
        result.put("sEcho", sEcho);
        result.put("iTotalRecords", videoPagination.getDataCount()); //total
        result.put("iTotalDisplayRecords", videoPagination.getDataCount()); //totalAfterFilter
        result.put("aaData", videoDTSList.toArray());
        setResContent2Json(response);
        return result;
    }

    /**
     * 调度
     *
     * @param id
     * @param name
     * @return
     */
    @RequestMapping("/dispatchBusinessId")
    @ResponseBody
    public Map<String, Object> dispatchBusinessId(String id, String name) {
        String dispatchBusinessId = null;
        String dispatchDesc = null;
        if (StringUtils.isNotBlank(name)) {
            if (name.indexOf(",") >= 0) {
                dispatchBusinessId = name.substring(0, name.lastIndexOf(","));
                dispatchDesc = name.substring(name.lastIndexOf(",") + 1);
            }
        }
        Video video = new Video();
        if (id == null) {
            logger.error("非法参数，id为空");
            return getFailMap("id参数不能为空!");
        }
        video.setId(ObjectUtils.toLong(id));
        if (StringUtils.isNotBlank(dispatchBusinessId)) {
            video.setDispatchBusinessId(dispatchBusinessId);
        } else {
            logger.error("非法参数，dispatchBusinessId为空");
            return getFailMap("至少选一个调度国家");
        }
        if (StringUtils.isNotBlank(dispatchDesc)) {
            logger.info(name + "f");
            video.setDispatchDesc(dispatchDesc);
        }
        try {
            videoService.dispatch(null, video);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return getFailMap("调度失败");
        }
        return getSuccessMap();
    }
}
